import React, { Component } from 'react';
import { connect } from 'dva';
import { Input, InputNumber, Button, Form, Table, Row, Col, Popover, Popconfirm, Modal, message } from 'antd';
const FormItem = Form.Item;

class ActivityProductTable extends Component {
  constructor() {
    super();
    this.state = {
      itemData: [],
      popoverVisible: false,
      itemQuery: {},
      dimensionCodePicTemp: new Map(),
    };
  }

  componentWillReceiveProps(...args) {
    if (args[0].data && args[0].data.length > 0 && this.state.itemData.length === 0) {
      this.setState({
        itemData: args[0].data.map((el, index) => {
          el.key = index + 1;
          return el;
        }),
      });
    }
  }

  getValue(callback) {
    const p = this;
    const { form } = this.props;
    const itemList = [];
    form.validateFields((err, fieldsItem) => {
      if (err) return;
      const keys = Object.keys(fieldsItem);
      const countKeys = {};
      keys.forEach((key) => {
        const num = key.split('r_')[1].split('_')[0];
        if (!countKeys[num]) countKeys[num] = true;
      });
      Object.keys(countKeys).forEach((count) => {
        const itemSingle = {};
        keys.forEach((key) => {
          if (key.match(`r_${count}_`)) {
            itemSingle[key.split(`r_${count}_`)[1]] = fieldsItem[key];
          }
        });
        // 补一下itemCode
        if (!itemSingle.itemCode) {
          itemSingle.itemCode = p[`r_${count}_itemCode_dom`].refs.input.value;
        }
        if (itemSingle.mainPic) delete itemSingle.mainPic;
        if (itemSingle.classicalId) {
          itemSingle.id = itemSingle.classicalId;
        }
        delete itemSingle.classicalId;
        itemList.push(itemSingle);
      });
      if (itemList.length < 1) {
        message.error('请至少填写一项商品信息');
        return;
      }
      if (callback) callback(itemList);
    });
  }

  addProduct() {
    const { itemData } = this.state;
    const { modalValues } = this.props;
    const itemLen = itemData.length;
    const lastId = itemLen < 1 ? 0 : itemData[itemData.length - 1].key;
    const newId = parseInt(lastId, 10) + 1;
    const newItem = {
      id: '',
      activityId: modalValues.id,
      key: newId,
      itemCode: '',
      itemId: '',
      name: '',
      priceRange: '',
    };
    itemData.push(newItem);
    this.setState({ itemData }, () => {
      setTimeout(() => {
      	document.getElementById('bottomDom').scrollIntoView();
        this[`r_${newId}_itemCode_dom`].refs.input.click();
      }, 0);
    });
  }

  handleDelete(key) {
    const newData = this.state.itemData.filter(el => el.key !== key);
    this.setState({ itemData: newData });
  }

  handleSelect(key, itemCode) {
    const { form, itemList } = this.props;
    const { itemData } = this.state;

    const source = itemList;

    // 先判断当前列表是否有相同的itemCode，有的话数量+1
    let isDuplicate = false;
    itemData.forEach((el, index) => {
      if (el.itemCode === itemCode) {
        isDuplicate = index + 1;
      }
    });
    if (isDuplicate) {
      Modal.info({
        title: '选择了列表已有的商品',
      });
      return;
    }
    // 否则新建一条记录
    source.forEach((value) => {
      if (value.itemCode.toString() === itemCode.toString()) {
        itemData.forEach((el) => {
          if (el.key.toString() === key.toString()) {
            el.itemCode = value.itemCode;
            el.itemId = value.id;
            el.name = value.name;
            el.priceRange = value.priceRange;
            el.mainPic = value.mainPic;
            el.classicalId = ''; // 重置条目id
          }
        });
        this.setState({ itemData }, () => {
          form.setFieldsValue({
            [`r_${key}_itemCode`]: value.itemCode,
            [`r_${key}_itemId`]: value.id,
            [`r_${key}_name`]: value.name,
            [`r_${key}_priceRange`]: value.priceRange,
            [`r_${key}_classicalId`]: '', // 重置条目id
          });
        });
      }
    });
  }

  handleSearch(num, size) {
    const { itemQuery } = this.state;
    const payload = { ...itemQuery, pageIndex: typeof num === 'number' ? num : 1 };
    if (typeof size === 'number') payload.itemPageSize = size;
    this.props.dispatch({
      type: 'sku/queryActivityItemList',
      payload,
    });
  }

  clearValue() {
    const { form } = this.props;
    this.setState({ itemData: [] }, () => {
      form.resetFields();
    });
  }

	generateDimensioncode(id){
		const p = this;
		const { itemData }= p.state;
		let activityIdtemp = 0;
		itemData.forEach((el) => {
			if(el.itemId == id && id != '' && el.activityId != undefined){
				activityIdtemp = el.activityId;
				const payload = {itemId:id,activityId:activityIdtemp}
				p.props.dispatch({
		      type: 'activity/getDimensioncode',
		      payload,
		      cb(data){
		      	p.setState({ dimensionCodePicTemp:p.state.dimensionCodePicTemp.set(id,data.data) });
		      }
		    });
			}
		});
	}

  render() {
    const p = this;
    const { form, itemList = [], parent, total, itemPageSize } = p.props;
    const { itemData, itemQuery } = p.state;
    const { getFieldDecorator } = form;

    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
    };

    // 注册props
    if (!parent.clearSkuValue) parent.clearSkuValue = this.clearValue.bind(this);
    if (!parent.getSkuValue) parent.getSkuValue = this.getValue.bind(this);

    function renderItemPopover(list, key, itemTotal) {
      let itemCode = null;
      let name = null;
      let buySite = null;

      function doSearch() {
        itemQuery.itemCode = itemCode.refs.input.value;
        itemQuery.name = name.refs.input.value;
        itemQuery.buySite = buySite.refs.input.value;
        p.setState({ itemQuery }, () => {
          p.handleSearch();
        });
      }

      function updateValue(selectedSkuCode) {
        p.handleSelect(key, selectedSkuCode);
        setTimeout(() => {
          p[`r_${key}_itemCode_dom`].refs.input.click();
        }, 0);
      }

      const paginationProps = {
        defaultPageSize: 20,
        showSizeChanger: true,
        total: itemTotal,
        showQuickJumper: true,
        pageSizeOptions: ['20', '30', '50', '100'],
        onShowSizeChange(current, size) {
          p.props.dispatch({
            type: 'sku/queryActivityItemList',
            payload: {
              pageIndex: current,
              itemPageSize: size,
            },
          });
        },
        onChange(page) {
          p.handleSearch(page, itemPageSize);
        },
      };

    const columns = [
        { title: '商品代码', dataIndex: 'itemCode', key: 'itemCode', width: '10%' },
        { title: '商品名称', dataIndex: 'name', key: 'name', width: '14%' },
        { title: '品牌', dataIndex: 'brand', key: 'brand', width: '8%' },
        { title: '所属分类', dataIndex: 'categoryName', key: 'categoryName', width: '8%', render(text) { return text || '-'; } },
        { title: '图片',
          dataIndex: 'mainPic',
          key: 'mainPic',
          width: '14%',
          render(text) { // 需要解决返回的mainPic的格式的问题
            let imgUrl = '';
            try {
              const imgObj = JSON.parse(text);
              imgUrl = imgObj.picList[0].url;
              const picContent = <img src={imgUrl} role="presentation" style={{ height: 600 }} />;
              return (
                <Popover title="主图预览" content={picContent}>
                  <img src={imgUrl} role="presentation" width="60" />
                </Popover>
              );
            } catch (e) {
              return '-';
            }
          },
        },
        { title: '是否可售', 
          dataIndex: 'isSale', 
          key: 'isSale', 
          width: '8%', 
          render(text) { 
	          	switch (text) {
	            case 1: return '可售';
	            default: return '不可销售';
	          } 
          }
        },
        { title: '商品状态', 
          dataIndex: 'status', 
          key: 'status', 
          width: '8%', 
          render(text) { 
	          	switch (text) {
		            case 0: return <font color="">新建</font>;
		            case 1: return <font color="blue">上架</font>;
		            case 2: return <font color="red">下架</font>;
		            case 3: return <font color="">同步</font>;
		            case -1: return <font color="">删除</font>;
		            default: return false;
	            }
	          }
          },
        { title: '操作', dataIndex: 'oper', key: 'oper', width: '8%', render(t, r) { return <a onClick={() => { updateValue(r.itemCode); }}>选择</a>; } },
      ];

      return (
        <div style={{ width: 800 }}>
          <Row gutter={20} style={{ width: 720 }}>
            <Col span="7">
              <FormItem
                label="商品代码"
                {...formItemLayout}
              >
                <Input
                  size="default"
                  placeholder="请输入商品代码"
                  ref={(c) => { itemCode = c; }}
                  defaultValue={itemQuery.itemCode}
                />
              </FormItem>
            </Col>
            <Col span="7">
              <FormItem
                label="商品名称"
                {...formItemLayout}
              >
                <Input
                  size="default"
                  placeholder="请输入商品名称"
                  ref={(c) => { name = c; }}
                  defaultValue={itemQuery.name}
                />
              </FormItem>
            </Col>
            <Col span="7">
              <FormItem
                label="采购站点"
                {...formItemLayout}
              >
                <Input
                  size="default"
                  placeholder="请输入采购站点"
                  ref={(c) => { buySite = c; }}
                  defaultValue={itemQuery.buySite}
                />
              </FormItem>
            </Col>
            <Col className="listBtnGroup" span="3" style={{ marginTop: 2 }}>
              <Button type="primary" onClick={doSearch}>查询</Button>
            </Col>
          </Row>
          <Row>
            <Table
              columns={columns}
              dataSource={list}
              size="small"
              bordered
              rowKey={record => record.id}
              pagination={paginationProps}
              scroll={{ x: '100%', y: 400 }}
            />
          </Row>
        </div>
      );
    }

    const modalTableProps = {
      columns: [
        { title: '商品代码',
          dataIndex: 'itemCode',
          key: 'itemCode',
          width: '20%',
          render(text, r) {
            return (
              <FormItem>
                {getFieldDecorator(`r_${r.key}_itemCode`, {
                  initialValue: text || undefined,
                  rules: [{ required: true, message: '请选择ITEM' }],
                })(
                  <Popover
                    content={renderItemPopover(itemList, r.key, total)}
                    title="搜索ITEM"
                    trigger="click"
                  >
                    <Input onFocus={p.handleSearch.bind(p)} placeholder="请选择ITEM" readOnly value={text || undefined} ref={(c) => { p[`r_${r.key}_itemCode_dom`] = c; }} />
                  </Popover>,
                )}
              </FormItem>
            );
          },
        },
        {
          title: '商品名称',
          dataIndex: 'name',
          key: 'name',
          width: '30%',
          render(text) { return text || '-'; },
        },
        {
          title: '商品图片',
          dataIndex: 'mainPic',
          key: 'mainPic',
          width: '15%',
          render(text) {
            let imgUrl = '';
            try {
              const imgObj = JSON.parse(text);
              imgUrl = imgObj.picList[0].url;
              const picContent = <img src={imgUrl} role="presentation" style={{ height: 600 }} />;
              return (
                <Popover title="主图预览" content={picContent}>
                  <img src={imgUrl} role="presentation" width="60" />
                </Popover>
              );
            } catch (e) {
              return '-';
            }
          },
        },
        {
          title: '生成二维码',
          dataIndex: 'activityItemDimensioncode',
          key: 'activityItemDimensioncode',
          width: '9%',
          render(text,r) {
      			if(text) return (<img src={text} role="presentation" style={{ height: 80 }} />);
      			return (
	          	<img onClick={ p.props.dcTitle=="修改" && p.state.dimensionCodePicTemp.get(r.itemId)==undefined ? p.generateDimensioncode.bind(p,r.itemId):"" }
	          		src={p.state.dimensionCodePicTemp.get(r.itemId) ? p.state.dimensionCodePicTemp.get(r.itemId):"http://iruhua.oss-cn-hangzhou.aliyuncs.com/26_1527666985606.jpg"} 
	          		role="presentation" style={{ height: 80 }} />
	          );
          },
        },
        {
          title: '价格区间',
          dataIndex: 'priceRange',
          key: 'priceRange',
          width: '10%',
          render(text) { return text || '-'; },
        },
        {
          title: '操作',
          key: 'operator',
          width: 60,
          render(text, r) {
            return (<Popconfirm title="确定删除?" onConfirm={p.handleDelete.bind(p, r.key)}>
              <a href="javascript:void(0)">删除</a>
              {getFieldDecorator(`r_${r.key}_classicalId`, { initialValue: r && r.id })(<Input style={{ display: 'none' }} />)}
            </Popconfirm>);
          },
        },
      ],
      dataSource: itemData,
      bordered: false,
      pagination: false,
    };
    return (
      <div>
        <Row style={{ paddingBottom: 10 }}>
          <Col style={{ float: 'left' }}>
            <span>活动明细信息</span>
          </Col>
          <Col style={{ float: 'right' }}>
            <Button type="primary" onClick={p.addProduct.bind(p)}>添加商品</Button>
          </Col>
        </Row>
        <Table {...modalTableProps} rowKey={record => record.key} />
        <div id="bottomDom"></div>
      </div>);
  }
}

function mapStateToProps(state) {
  const { itemList, itemTotal, itemPageSize } = state.sku;
  return {
    itemList,
    total: itemTotal,
    itemPageSize,
  };
}

export default connect(mapStateToProps)(Form.create()(ActivityProductTable));
